﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using HZManager.Models;
using PagedList;
using System.Data.Entity.Infrastructure;
using HZManager.ViewModels;

namespace HZManager.Controllers
{
    public class InventoryRecordController : Controller
    {
        private InventoryContext db = new InventoryContext();

        // GET: InventoryRecord
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, int? id, int? InventoryItemRecordID)
        {


            ViewBag.CurrentSort = sortOrder;//保持分页时排列顺序相同
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "customer_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
            var InventoryRecords = from s in db.InventoryRecords
                                   select s;
            if (searchString != null)
            {

                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }
            ViewBag.CurrentFilter = searchString;

            if (!String.IsNullOrEmpty(searchString))
            {
                InventoryRecords = InventoryRecords.Where(s =>
                s.Customer.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "customer_des":
                    InventoryRecords = InventoryRecords.OrderByDescending(s => s.Customer);
                    break;
                case "Date":
                    InventoryRecords = InventoryRecords.OrderBy(s => s.Date);
                    break;
                case "date_desc":
                    InventoryRecords = InventoryRecords.OrderByDescending(s => s.Date);
                    break;
                default:
                    InventoryRecords = InventoryRecords.OrderBy(s => s.Customer);
                    break;
            }
            int pageSize = 3;
            int pageNumber = (page ?? 1);
            return View(InventoryRecords.ToPagedList(pageNumber, pageSize));

            // return View(InventoryRecords.ToList());
        }

        // GET: InventoryRecord/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            InventoryRecord inventoryRecord = db.InventoryRecords.Find(id);
            if (inventoryRecord == null)
            {
                return HttpNotFound();
            }
            return View(inventoryRecord);
        }

        // GET: InventoryRecord/Create
        public ActionResult Create()
        {
            PopulateReasonsDropDownList();
            return View();
        }

        // POST: InventoryRecord/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "InventoryRecordID,Date,Customer,ResponsibleOfficer,ReasonID")] InventoryRecord inventoryRecord)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.InventoryRecords.Add(inventoryRecord);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.)
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
            }
            PopulateReasonsDropDownList(inventoryRecord.ReasonID);

            return View(inventoryRecord);
        }

        // GET: InventoryRecord/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            InventoryRecord inventoryRecord = db.InventoryRecords.Find(id);
            if (inventoryRecord == null)
            {
                return HttpNotFound();
            }
            PopulateReasonsDropDownList(inventoryRecord.ReasonID);
            return View(inventoryRecord);
        }

        // POST: InventoryRecord/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "InventoryRecordID,Date,Customer,ResponsibleOfficer,ReasonID")] InventoryRecord inventoryRecord)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(inventoryRecord).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.)
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
            }
            PopulateReasonsDropDownList(inventoryRecord.ReasonID);
            return View(inventoryRecord);
        }
        private void PopulateReasonsDropDownList(object selectedReason =null)
        {
            var ReasonsQuery = from d in db.Reasons
                                   orderby d.Name
                                   select d;
            ViewBag.ReasonID = new SelectList(ReasonsQuery, "ReasonID",
            "Name", selectedReason);
        }

        // GET: InventoryRecord/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            InventoryRecord inventoryRecord = db.InventoryRecords.Find(id);
            if (inventoryRecord == null)
            {
                return HttpNotFound();
            }
            return View(inventoryRecord);
        }

        // POST: InventoryRecord/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            InventoryRecord inventoryRecord = db.InventoryRecords.Find(id);
            db.InventoryRecords.Remove(inventoryRecord);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
